<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>列表排序</title>
    <script type="text/javascript" src="../js/vue.js"></script>
    <script type="text/javascript">
      Vue.config.productionTip = false;
    </script>
  </head>
  <body>
    <div id="root">
      <h2>人员列表</h2>
      <input type="text" placeholder="请输入名字筛选" v-model="inputName" />
      <button @click="sortType = 1">年龄升序</button>
      <button @click="sortType = 2">年龄降序</button>
      <button @click="sortType = 0">恢复顺序</button>
      <ul>
        <li v-for="p in filPersons" :key="p.id">{{p.name}}-{{p.age}}</li>
      </ul>
    </div>
  </body>

  <script type="text/javascript">
    const vm = new Vue({
      el: "#root",
      data: {
        inputName: "",
        sortType: 0, //默认0，升序1，降序2
        //原数据不能动！后续还要还原
        persons: [
          {
            id: "001",
            name: "张三",
            age: 18,
          },
          {
            id: "002",
            name: "张思",
            age: 15,
          },
          {
            id: "003",
            name: "李四",
            age: 26,
          },
          {
            id: "004",
            name: "李武",
            age: 22,
          },
        ],
      },
      computed: {
        //计算属性实现，计算的原因是更改了sortType，计算属性配置的任何一个属性发生变化，都会重新计算
        filPersons() {
          //先接收计算后的属性
          const filterList = this.persons.filter((e) => {
            return e.name.indexOf(this.inputName) !== -1;
          });
          //判断是否需要排序
          if (this.sortType > 0) {
            filterList.sort((p1, p2) => {
              return this.sortType === 1 ? p1.age - p2.age : p2.age - p1.age;
            });
          }
          return filterList;
        },
      },
    });
  </script>
</html>
